
import requests
from django.shortcuts import render
from weather_app.forms import CityForm 
from .models import City



def index(request):


    url_weather='http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&lang=ru&appid=fae36f9cfeaf9eccccd6dc085a0bf33e'
    city = 'Tomsk'
    if request.method == 'POST':
        form=CityForm(request.POST)
        form.save()
        
    form = CityForm()
    
    cities = City.objects.all()
    
    weathers_data = []
    
    for city in cities:
        
        r = requests.get(url_weather.format(city)).json()
        
        city_weather = {
            'city': city.name,
            'temperature': r['main']['temp'],
            'description': r['weather'][0]['description'],
            'icon': r['weather'][0]['icon'],
        }
    
        weathers_data.append(city_weather)
    
    context = {'weathers_data': weathers_data, 'form': form}
    return render(request, 'weather_app/index.html', context)   




